package br.ufrpe.bsi.pvs;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import br.ufrpe.bsi.pvs.patterns.Observable;
import br.ufrpe.bsi.pvs.patterns.Observer;

/** all responses from system core are stored here, in-memory */
public class ResponseQueue implements Observable {

	public static final ResponseQueue INSTANCE = new ResponseQueue();
	
	private Map<String, Object> responseQueue = new LinkedHashMap<>();
	
	private List<Observer> observers = new ArrayList<>();
	
	private ResponseQueue() {}
	
	public Object getResponse(String index) {
		Object response = responseQueue.get(index);
		if (response != null) {
			responseQueue.remove(index);
			return response;
		} else
			return null;
	}
	
	public void queueResponse(String index, Object response) {
		responseQueue.put(index, response);
		notifyObs();
	}

	@Override
	public void register(Observer o) {
		observers.add(o);
	}

	@Override
	public void remove(Observer o) {
		observers.remove(o);
	}

	@Override
	public void notifyObs() {
		for(Observer o : observers)
			o.update();
	}
}
